package forum.service.rpc;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.foreveross.springboot.dubbo.utils.BeanHelper;
import forum.domain.Resources;
import forum.domain.Role;
import forum.repository.ResourcesRepository;
import forum.repository.RoleRepository;
import forum.repository.RoleResourcesRepository;
import forum.service.rpc.api.RoleResourcesService;
import forum.service.rpc.api.RoleService;
import forum.service.tools.BaseSearch;
import forum.service.tools.SearchDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.QueryParam;
import java.util.Arrays;
import java.util.List;

/**
 * Created by Administrator on 2017/4/5.
 */
@org.springframework.stereotype.Service("roleService")
public class RoleServiceImpl implements RoleService {


    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private RoleResourcesRepository roleResourcesRepository;

    @Override
    public Object getRoleList(@QueryParam("page") @DefaultValue("0") int page,
                              @QueryParam("size") @DefaultValue("50") int size,
                              @QueryParam("sort") @DefaultValue("sort=roleid,desc") String sort,
                              @QueryParam("operation") @DefaultValue("operation=eq") String operation,
                              @QueryParam("key") @DefaultValue("key=roleid") String key,
                              @QueryParam("value") @DefaultValue("1") String value) {
//        logger.debug("get roles: {} . -> {}", "GET /api/v1/roles/", sort);

        // 简单适配, 暂无严谨性
        sort = sort.replaceAll("sort=", "").trim(); // sort=firstname,desc
        String[] sort_arr = sort.split(",");
        Sort.Direction direction;
        if (sort_arr[1] != null && "desc".equals(sort_arr[1])) {
            direction = Sort.Direction.DESC;
        } else {
            direction = Sort.Direction.ASC;
        }
        String[] properties = sort_arr[0].split("&");

        Sort _sort = new Sort(direction, Arrays.asList(properties));
        Pageable pageable = new PageRequest(page, size, _sort);

        if(StringUtils.isEmpty(key) || StringUtils.isEmpty(operation)  || StringUtils.isEmpty(value)){
            logger.info("提示: key或者operation或者value为空 ");

        }

        if(!StringUtils.isEmpty(key) && !StringUtils.isEmpty(operation)  && !StringUtils.isEmpty(value)){
            logger.info("提示: key并且operation并且value都不为空 ");
            return roleRepository.findAll(new BaseSearch<Role>(new SearchDto(key,operation, value)),pageable);
        }

        return  roleRepository.findAll(pageable);

    }

    @Override
    public Object getRoleById(Integer id) {
        Role role = roleRepository.findOne(id);
        return role;
    }

    @Override
    public Object createRole(Role role) {
        if (role != null) {
            List<Role> list =  roleRepository.findByRolename(role.getRolename());
            if (list != null && list.size() != 0) {
                return role.getRolename() + " 角色名已经存在！";
            }
            roleRepository.save(role);
        }
        return role;
    }

    @Override
    public Object updateRoleById(@RequestBody Role jsonObj) {
        Role role = null;
        if (jsonObj.getRoleid() != null && jsonObj.getRoleid() > 0) {
            role = roleRepository.findOne(jsonObj.getRoleid());
            if (role==null){
                return "没找到该ID的对象";
            }
            BeanHelper.mapPartOverrider(role, jsonObj);
            roleRepository.save(role);
        }else {
            return "id为空";
        }
        return role;
    }


    @Override
    @Transactional
    public Object deleteRoleByIds(Integer[] ids) {
        boolean flag = false;
        if (ids != null && ids.length > 0) {
            for (int i=0;i<ids.length;i++){
                roleRepository.delete(ids[i]);
                roleRepository.deleteByRoleid(ids[i]);
//                Resources resources =  resourcesRepository.findOne(ids[i]);
//                if(resources.getParentid()==0) {//父级菜单
                roleResourcesRepository.deleteByRoleid(ids[i]);
//                    List<Resources> _resources = resourcesRepository.findByParentid(resources.getResourcesid());
//                }

            }

//            userRoleRepository.deleteUserRolesByUserIds(ids);
            flag = true;
        }
        return flag;
    }

}
